package com.cat.admin.controller;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cat.admin.service.SysMenuService;
import com.cat.common.entity.SysMenu;
import com.cat.common.entity.UserInfo;
import com.cat.common.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author dd-cat
 * @version 1.0
 * @date 2020-11-24 12:06
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/menu")
@Api(value = "menu", tags = "菜单模块")
public class SysMenuController {
    private final SysMenuService menuService;

    @GetMapping("list")
    public List<SysMenu> list() {
        return menuService.list();
    }

    @GetMapping("tree")
    public List<Tree<Long>> tree() {
        Set<SysMenu> all = new HashSet<>(menuService.list());
        return menuService.treeMenu(all);
    }

    @GetMapping
    @ApiOperation("当前用户菜单")
    public List<Tree<Long>> getUserMenus() {
        Set<SysMenu> all = new HashSet<>();
        UserInfo user = SecurityUtils.getUser();
        user.getRoles().forEach(roleId ->
                all.addAll(
                        menuService.findMenuByRoleId(roleId).stream()
                                .filter(menu -> !"2".equals(menu.getType()))
                                .collect(Collectors.toList())
                )
        );
        return menuService.treeMenu(all);
    }

    /**
     * 通过ID查询
     *
     * @param id ID
     */
    @GetMapping("/{id}")
    public SysMenu getById(@PathVariable Integer id) {
        return menuService.getById(id);
    }

    /**
     * 添加
     *
     * @param menu 实体
     */
    @PostMapping
    public boolean save(@Valid @RequestBody SysMenu menu) {
        return menuService.save(menu);
    }

    /**
     * 删除
     *
     * @param ids ids
     */
    @DeleteMapping("/{ids}")
    public boolean removeByIds(@PathVariable List<Long> ids) {
        return menuService.removeByIds(ids);
    }

    /**
     * 编辑
     *
     * @param sysMenu 实体
     */
    @PutMapping
    public boolean update(@Valid @RequestBody SysMenu sysMenu) {
        UserInfo user = SecurityUtils.getUser();
        sysMenu.setUpdateTime(LocalDateTime.now());
        sysMenu.setUpdateBy(user.getUsername());
        return menuService.updateById(sysMenu);
    }
}
